<script setup lang="ts">
import { ref, defineProps, computed } from 'vue'
import { showToast, showDialog, Icon, Field, Button } from 'vant'
import { useChartStore } from '@/store/chart'

const props = defineProps({
  embed: { type: Boolean, default: false }
})

const chartStore = useChartStore()
const userRequirement = ref('')

// 计算属性从store获取数据
const isGenerating = computed(() => chartStore.isGenerating)
const generatedImageUrl = computed(() => chartStore.currentImageUrl)
const history = computed(() => chartStore.history)

// 示例需求
const examples = [
  {
    title: '数据库备份与恢复系统',
    description: '管理员执行数据库备份、存储备份文件、恢复备份的时序图'
  },
  {
    title: '数据库用户权限管理系统',
    description: '管理员创建用户、分配权限、修改权限、删除用户的用例图'
  },
  {
    title: '数据库表结构设计工具',
    description: '表、字段、关系之间的类图，展示如何通过工具设计数据库表结构'
  },
  {
    title: '数据库事务处理流程',
    description: '事务从开始到提交或回滚的状态转换图，包括锁的获取与释放'
  },
  {
    title: '数据库查询优化流程',
    description: '用户提交查询请求、查询分析、优化建议生成的活动图'
  },
  {
    title: '数据库监控系统',
    description: '监控数据库性能指标、触发警报、记录日志的时序图'
  },
  {
    title: '数据库迁移系统',
    description: '从源数据库导出数据、转换数据格式、导入目标数据库的用例图'
  }
]

const generateChart = async () => {
  if (!userRequirement.value.trim()) {
    showToast('请输入图表需求描述')
    return
  }
  
  chartStore.setGenerating(true)
  
  try {
    const formData = new URLSearchParams()
    formData.append('message', userRequirement.value)
    
    const response = await fetch(`${import.meta.env.VITE_BASE_URL}/api/agent/plantuml`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: formData
    })
    
    if (!response.ok) {
      throw new Error(`生成失败: ${response.status}`)
    }
    
    const result = await response.json()
    
    // 检查响应格式
    if (result.code !== 0) {
      throw new Error(result.message || '生成失败')
    }
    
    if (!result.data) {
      throw new Error('未获取到图片URL')
    }
    
    const imageUrl = result.data
    chartStore.setCurrentImageUrl(imageUrl)
    chartStore.addToHistory(userRequirement.value, imageUrl)
    
    showToast('图表生成成功')
  } catch (error) {
    console.error('生成图表失败:', error)
    showToast('生成图表失败，请重试或换个描述方式')
  } finally {
    chartStore.setGenerating(false)
  }
}

const downloadImage = async () => {
  if (!generatedImageUrl.value) return
  
  try {
    const response = await fetch(generatedImageUrl.value)
    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `chart-${Date.now()}.png`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(url)
    showToast('图片下载成功')
  } catch (error) {
    console.error('下载失败:', error)
    showToast('下载失败')
  }
}

const clearAll = () => {
  showDialog({
    title: '清空确认',
    message: '确定要清空所有内容和历史记录吗？',
    showCancelButton: true,
    cancelButtonText: '取消',
    confirmButtonText: '确定',
    confirmButtonColor: '#4080ff',
  }).then(() => {
    userRequirement.value = ''
    chartStore.clearHistory()
    showToast('已清空')
  }).catch(() => {})
}

const loadExample = (example: any) => {
  userRequirement.value = example.description
}

const loadFromHistory = (item: any) => {
  userRequirement.value = item.requirement
  chartStore.setCurrentImageUrl(item.imageUrl)
}

const removeHistoryItem = (item: any, event: Event) => {
  event.stopPropagation()
  showDialog({
    title: '删除确认',
    message: '确定要删除这条历史记录吗？',
    showCancelButton: true,
    cancelButtonText: '取消',
    confirmButtonText: '删除',
    confirmButtonColor: '#ee0a24',
  }).then(() => {
    chartStore.removeHistoryItem(item.id)
    showToast('已删除')
  }).catch(() => {})
}

const formatTimestamp = (timestamp: number) => {
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN')
}
</script>

<template>
  <div class="chart-container" :class="{ embed: props.embed }">
    <div class="web-header">
      <div class="title">一键作图</div>
      <div class="actions">
        <div class="clear-button" @click="clearAll">
          <Icon name="delete-o" size="16" />
          <span>清空</span>
        </div>
      </div>
    </div>
    
    <div class="chart-content">
      <div class="input-section">
        <div class="section-header">
          <h3>需求描述编辑器</h3>
        </div>
        
        <div class="examples">
            <span class="example-label">示例：</span>
            <button 
              v-for="example in examples" 
              :key="example.title"
              class="example-btn"
              @click="loadExample(example)"
            >
              {{ example.title }}
            </button>
          </div>

        <Field
          v-model="userRequirement"
          type="textarea"
          rows="6"
          class="requirement-textarea"
          placeholder="请描述您想要生成的图表，例如：学生管理系统的用户登录流程时序图，包含学生、系统、数据库之间的交互..."
          autosize
        />
        
        <div class="tips">
          <Icon name="info-o" size="14" color="#1989fa" />
          <span>提示：描述越详细，生成的图表越准确。可以指定图表类型（时序图、用例图、类图等）和主要元素。</span>
        </div>
        
        <div class="action-buttons">
          <Button 
            type="primary" 
            :loading="isGenerating"
            :disabled="!userRequirement.trim()"
            @click="generateChart"
            class="generate-btn"
          >
            <Icon name="photo-o" size="16" />
            {{ isGenerating ? '生成中...' : '生成图表' }}
          </Button>
        </div>
      </div>
      
      <div class="preview-section">
        <div class="section-header">
          <h3>图表预览</h3>
          <Button 
            v-if="generatedImageUrl"
            type="success"
            size="small"
            @click="downloadImage"
            class="download-btn"
          >
            <Icon name="down" size="14" />
            下载图片
          </Button>
        </div>
        
        <div class="preview-container">
          <div v-if="!isGenerating && !generatedImageUrl" class="preview-placeholder">
            <Icon name="photo-o" size="64" color="#c8c9cc" />
            <p>请输入图表需求描述并点击生成图表</p>
            <div class="placeholder-examples">
              <p>您可以描述：</p>
              <ul>
                <li>• 系统功能的时序图</li>
                <li>• 用户角色的用例图</li>
                <li>• 数据模型的类图</li>
                <li>• 业务流程的活动图</li>
              </ul>
            </div>
          </div>
          
          <!-- 生成中状态 -->
          <div v-else-if="isGenerating" class="generating-state">
            <Icon name="loading" size="48" color="#1989fa" class="loading-icon" />
            <h4>正在生成图表中...</h4>
            <p>正在分析您的需求并生成相应的图表</p>
          </div>
          
          <div v-else class="preview-image">
            <img :src="generatedImageUrl" alt="Generated Chart" @error="showToast('图片加载失败')" />
          </div>
        </div>
      </div>
      
      <!-- 历史记录 -->
      <div v-if="history.length > 0" class="history-section">
        <div class="section-header">
          <h3>历史记录</h3>
          <span class="history-count">{{ history.length }} 条记录</span>
        </div>
        
        <div class="history-list">
          <div 
            v-for="item in history" 
            :key="item.id"
            class="history-item"
            @click="loadFromHistory(item)"
          >
            <div class="history-preview">
              <img :src="item.imageUrl" alt="History Chart" />
            </div>
            <div class="history-info">
              <div class="history-title">图表生成</div>
              <div class="history-description">{{ item.requirement.substring(0, 80) }}{{ item.requirement.length > 80 ? '...' : '' }}</div>
              <div class="history-meta">
                <span class="history-mode">需求生成</span>
                <span class="history-time">{{ formatTimestamp(item.timestamp) }}</span>
              </div>
            </div>
            <div class="history-actions">
              <Icon 
                name="delete-o" 
                size="16" 
                color="#ee0a24"
                class="delete-icon"
                @click="removeHistoryItem(item, $event)"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.chart-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 600px;
  background-color: #fff;
  
  .web-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 24px;
    border-bottom: 1px solid #ebeef5;
    background-color: #fff;
    position: sticky;
    top: 0;
    z-index: 100;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
    
    .title {
      font-size: 18px;
      font-weight: 500;
      color: #333;
    }
    
    .actions {
      .clear-button {
        display: flex;
        align-items: center;
        gap: 6px;
        padding: 8px 16px;
        background-color: #f5f5f5;
        border-radius: 4px;
        color: #606266;
        font-size: 14px;
        cursor: pointer;
        transition: all 0.2s;
        
        &:hover {
          background-color: #e8e8e8;
        }
      }
    }
  }
  
  .chart-content {
    flex: 1;
    padding: 24px;
    overflow-y: auto;
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
    
    .section-header {
      display: flex;
      gap: 8px;
      justify-content: space-between;
      margin-bottom: 16px;
      
      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
        color: #333;
      }
      
      .history-count {
        font-size: 12px;
        color: #666;
        background: #f5f5f5;
        padding: 2px 8px;
        border-radius: 12px;
      }
    }

    .examples {
      display: flex;
      align-items: center;
      gap: 8px;
      flex-wrap: wrap;
      margin-bottom: 16px;
      
      .example-label {
        font-size: 12px;
        color: #666;
      }
      
      .example-btn {
        padding: 4px 8px;
        background: #f0f9ff;
        color: #1989fa;
        border: 1px solid #b3d8ff;
        border-radius: 4px;
        font-size: 12px;
        cursor: pointer;
        transition: all 0.2s;
        white-space: nowrap;
        
        &:hover {
          background: #e6f7ff;
          border-color: #91d5ff;
        }
      }
    }
    
    .input-section {
      .requirement-textarea {
        margin-bottom: 12px;
        
        :deep(.van-field__control) {
          font-size: 14px;
          line-height: 1.6;
          background: #f8f9fa;
          border-radius: 8px;
          padding: 16px;
          border: 1px solid #e1e5e9;
          
          &:focus {
            border-color: #1989fa;
            box-shadow: 0 0 0 2px rgba(25, 137, 250, 0.1);
          }
        }
      }
      
      .tips {
        display: flex;
        align-items: flex-start;
        gap: 8px;
        padding: 12px;
        background: #f0f9ff;
        border-radius: 8px;
        margin-bottom: 16px;
        font-size: 13px;
        color: #666;
        line-height: 1.5;
      }
      
      .action-buttons {
        display: flex;
        gap: 12px;
        
        .generate-btn {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 12px 24px;
          background: linear-gradient(135deg, #1989fa, #40a9ff);
          border: none;
          border-radius: 8px;
          font-weight: 500;
          font-size: 15px;
          
          &:hover:not(:disabled) {
            background: linear-gradient(135deg, #1670cc, #369eea);
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(25, 137, 250, 0.3);
          }
          
          &:disabled {
            opacity: 0.6;
          }
        }
      }
    }
    
    .preview-section {
      .section-header {
        flex-direction: row !important;
        align-items: center;
      }
      
      .preview-container {
        border: 2px dashed #e1e5e9;
        border-radius: 12px;
        min-height: 400px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #fafbfc;
        transition: all 0.3s;
        
        &:hover {
          border-color: #1989fa;
          background: #f0f9ff;
        }
        
        .preview-placeholder {
          text-align: center;
          color: #666;
          padding: 20px;
          
          p {
            margin: 16px 0;
            font-size: 14px;
          }
          
          .placeholder-examples {
            margin-top: 20px;
            
            p {
              font-size: 13px;
              color: #888;
              margin-bottom: 8px;
            }
            
            ul {
              text-align: left;
              display: inline-block;
              font-size: 12px;
              color: #999;
              line-height: 1.8;
              
              li {
                margin-bottom: 4px;
              }
            }
          }
        }
        
        .generating-state {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 400px;
          text-align: center;
          padding: 20px;
          
          .loading-icon {
            animation: rotate 1s linear infinite;
            margin-bottom: 16px;
          }
          
          h4 {
            margin: 0 0 8px 0;
            color: #1989fa;
            font-size: 16px;
          }
          
          p {
            margin: 8px 0;
            color: #666;
            font-size: 14px;
          }
        }
        
        .preview-image {
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 20px;
          
          img {
            max-width: 100%;
            max-height: 100%;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
          }
        }
      }
      
      .download-btn {
        display: flex;
        align-items: center;
        gap: 6px;
        background: #52c41a;
        border: none;
        
        &:hover {
          background: #389e0d;
          transform: translateY(-1px);
          box-shadow: 0 2px 8px rgba(82, 196, 26, 0.3);
        }
      }
    }
    
    .history-section {
      grid-column: 1 / -1;
      
      .history-list {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
        gap: 16px;
        
        .history-item {
          border: 1px solid #e1e5e9;
          border-radius: 12px;
          padding: 16px;
          cursor: pointer;
          transition: all 0.2s;
          background: #fff;
          position: relative;
          
          &:hover {
            border-color: #1989fa;
            box-shadow: 0 2px 8px rgba(25, 137, 250, 0.15);
            transform: translateY(-2px);
          }
          
          .history-preview {
            width: 100%;
            height: 120px;
            overflow: hidden;
            border-radius: 8px;
            background: #f8f9fa;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 12px;
            
            img {
              max-width: 100%;
              max-height: 100%;
              object-fit: contain;
            }
          }
          
          .history-info {
            .history-title {
              font-size: 14px;
              font-weight: 600;
              color: #333;
              margin-bottom: 4px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
            
            .history-description {
              font-size: 12px;
              color: #666;
              line-height: 1.4;
              margin-bottom: 8px;
              overflow: hidden;
              text-overflow: ellipsis;
              display: -webkit-box;
              -webkit-line-clamp: 2;
              -webkit-box-orient: vertical;
            }
            
            .history-meta {
              display: flex;
              flex-wrap: wrap;
              gap: 8px;
              font-size: 11px;
              
              span {
                padding: 2px 6px;
                border-radius: 4px;
                background: #f5f5f5;
                color: #666;
                
                &.history-mode {
                  background: #e6f7ff;
                  color: #1989fa;
                }
                
                &.history-time {
                  background: #f5f5f5;
                  color: #999;
                }
              }
            }
          }
          
          .history-actions {
            position: absolute;
            top: 12px;
            right: 12px;
            
            .delete-icon {
              padding: 4px;
              cursor: pointer;
              border-radius: 4px;
              transition: all 0.2s;
              
              &:hover {
                background: rgba(238, 10, 36, 0.1);
              }
            }
          }
        }
      }
    }
  }
  
  &.embed {
    .web-header {
      position: static !important;
      box-shadow: none;
    }
  }
  
  @media (max-width: 1200px) {
    .chart-content {
      grid-template-columns: 1fr;
      gap: 16px;
    }
  }
}
</style> 